import React, { useRef, useEffect, useState } from "react";
import { Select, Space, Input, Form, Button, Spin, message } from 'antd';
import { UndoOutlined, SearchOutlined } from "@ant-design/icons";
import { CmdbContent, CmdbHeader, useModelAssociateType, useModelList, HcpPoolSelect} from "@/components";
import hcpUtils from '@/utils/hcpUtils';
import cmdbres from '@/data/cmdbres';
import request from '@/utils/request';
import "./index.less"
import G6 from '@antv/g6';
import registerEdge from './config/register-edge';
import registerNode from './config/register-node';
import { G6ToolBar, G6Menu, G6Tooltip } from './config/register-plugins';
import { defaultNodeConfig, defaultEdgeConfig, defaultLayout, defaultTBLayout } from "./config/default";
import { queryRegion } from './config/dataSource';
import { getGraphData, addNodeServer, getModule, mockData } from "./config/utils";
import HelpTipModal from './components/helpTipModal';
import DetailsModal from './components/detailsModal';
import MonitorModal from './components/monitorModal';
import AssetsAlarm from './components/assetsAlarm/index';
import ResourceAlarm from './components/resourceAlarm/index';
const GRAPH_ID = "resource-monitor-graph-container"

const monitorTopology = ({ history, match, location }) => {
  const [form] = Form.useForm();
  const [module, moduleData, moduleLoading] = useModelList();
  const domRef = useRef(null);
  const graphRef = useRef(null);
  let graph = graphRef.current;
  const [showHelp, setShowHelp] = useState(false);
  const [detailInfo, setDetailInfo] = useState({});
  const [showDetailModal, setShowDetailModal] = useState(false);
  const [showMonitorModal, setShowMonitorModal] = useState(false);
  const [showAlarmModal, setShowAlarmModal] = useState(false);
  const [showPhysicalAlarmModal, setShowPhysicalAlarmModal] = useState(false);
  const [graphData, setGraphData] = useState();
  const [region, setRegion] = useState();
  const [regionData, setRegionData] = useState([]);
  const [graphLoading, setGraphLoading] = useState(false);
  const [reload, setReload] = useState(0);

  useEffect(() => {
    queryRegion()
      .then((data) => {
        setRegionData(data);
        setRegion(data?.[0]);
        setReload(reload+1);
      })
      .catch((e) => {
          setRegion([]);
          throw e;
      });
  }, []);

  useEffect(() => {
    if(reload && moduleData.length) getGraphData({region, moduleData, setGraphLoading, setGraphData});
  }, [moduleData, reload]);

  useEffect(() => {
    if(!graph) {
      graph = createGraphic();
    }
    bindEvents();
    return () => {
      if(graph) {
        graph.destroy();
      }
    };
  },[])

  useEffect(() => {
      if(!(graph && graphData)) return;
      graph.data(graphData);
      graph.render();
      graph.fitCenter();
      // 关闭局部渲染解决缩放或者拖拽引起的残影问题（关闭会影响性能，临时解决办法）
      graph.get('canvas').set('localRefresh', false);
  }, [graphData])

  const createGraphic = () => {
    // 注册自定义节点
    registerEdge(G6);
    // 注册自定义边
    registerNode(G6);

    const container = document.getElementById(GRAPH_ID);
    const tree = new G6.TreeGraph({
      container: domRef.current,
      linkCenter: true,
      width: container.offsetWidth,
      height: container.offsetHeight,
      defaultNode: defaultNodeConfig,
      defaultEdge: defaultEdgeConfig,
      layout: defaultLayout,
      modes: {
        default: [
          'collapse-expand',
          'scroll-canvas',
          'drag-canvas',
          'drag-node',
          {
            type: 'zoom-canvas',
            sensitivity: 1
          },
        ],
      },
      plugins: [
        new G6.Grid(),
        new G6.Minimap({
          size: [200, 150],
        }),
        G6Menu(G6, menuHandles),
        G6ToolBar(G6, toolBarHandles),
        G6Tooltip(G6),
      ],
    });

    graphRef.current = tree;
    return tree;
  };

  const bindEvents = () => { 
    graph.on('node:dblclick', (e)=> {
      const item = e.item;
      const model = item.getModel();
      if(!model.graphType || model.children?.length > 0) return false;
      
      // const lastPoint = graph.getCanvasByPoint(0, 0);
      if(model.graphType == "phy_server") {// 查询宿主机下的云主机
        const { serverModule } = getModule(moduleData);
        setGraphLoading(true);
        addNodeServer(model, serverModule, (servers) => {
          if(!(servers && servers.length)){
            message.info("未查到关联的云主机！");
            setGraphLoading(false);
            return false;
          }
          console.log(servers)
          if(!model.children) {
            graph.updateChildren(servers, model.id);
            graph.updateItem(item, model);
            item.toFront();
            // const newPoint = graph.getCanvasByPoint(0, 0);
            // graph.translate(lastPoint.x - newPoint.x, lastPoint.y - newPoint.y);
            graph.render();
          }
          setGraphLoading(false);
        });
      }
    })
  }
  const menuHandles = {
    queryDetail(item) {
      const info = item.getModel();
      setDetailInfo(info);
      setShowDetailModal(true);
    },
    queryMonitor(item) {
      const info = item.getModel();
      setDetailInfo(info);
      setShowMonitorModal(true);
    },
    queryAlarm(item) {
      const info = item.getModel();
      setDetailInfo(info);
      if(info.graphType == "phy_server") {
        setShowPhysicalAlarmModal(true);
      } else {
        setShowAlarmModal(true);
      }
    },
  };
  
  const toolBarHandles = {
    defaultSize () {
      graph.zoomTo(1);
    },
    // 缩小
    zoomOut () {
      graph.zoom(0.9);
    },
    // 放大
    zoomIn () {
      graph.zoom(1.1);
    },
    relocation() {
      graph.fitCenter();
    },
    graphHelp () {
      setShowHelp(true);
    },
    mindmap () {
      graph.edge((edge) => {
        edge.type = 'line-lr';
        return edge;
      });
      graph.updateLayout(defaultLayout);
      graph.render();
      graph.fitCenter();
    },
    dendrogram () {
      graph.edge((edge) => {
        edge.type = 'line-tb';
        return edge;
      });
      graph.updateLayout(defaultTBLayout);
      graph.render();
      graph.fitCenter();
    }
  };

  return (
    <CmdbContent>
      <CmdbHeader title={"系统资源监控"} />
      <section className="hcp__page">
        <section className="hcp__page__container" style={{backgroundColor: 'white', padding: 10}}>
          <div
            style={{
              backgroundColor: '#f0f5ff',
              border: '1px solid #f0f4ff',
              marginBottom: 10,
              padding: '12px 22px',
              display: 'flex'
            }}
          >
            <span className="iconfont icon-confirm-warning" style={{width: 22, marginTop: 6}}></span>
            <p style={{lineHeight: 2, margin: 0}}>
              须知：<br/>
              1.系统资源监控主要实现对宿主机、云主机资源的拓扑视图、监控视图、告警信息展示，便于了解虚拟资源运行状况。<br/>
              {/* 2.可用域展示的告警数=该节点下宿主机告警数+云主机告警数；宿主机展示的告警数=该节点告警数+子节点告警数； */}
            </p>
          </div>
          <div style={{ overflow: 'hidden' }}>
              <section style={{float: "left", padding: "5px 10px 10px 0"}}>
                  <Space>
                      <Button type="primary" onClick={() => {setReload(reload+1)}} >
                          刷新
                      </Button>
                  </Space>
              </section>
              <section className="hcp__search__collapse hcp_search_bar" style={{display: 'inline-block', textAlign: "right",  paddingTop: "5px"}}>
                  <section className="hcp__form">
                    <Select
                      placeholder="请选择资源池"
                      style={{ width: 150, marginRight: 10, textAlign: 'left' }}
                      onChange={(value, option) => {
                        setRegion(option.itemData);
                      }}
                      value={region?.id}
                      showSearch
                      filterOption={(input, option) =>
                          option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      }
                      // getPopupContainer={(triggerNode) => triggerNode.parentElement}
                    >
                      {regionData.map((item, index) => (
                          <Select.Option key={index} value={item.id} itemData={item}>
                              {item.regionName}
                          </Select.Option>
                      ))}
                    </Select>
                    <Space>
                      <Button type="primary" icon={<SearchOutlined />} onClick={() => {setReload(reload+1)}} title="刷新"></Button>
                      <Button 
                        onClick={()=>{
                          if(regionData?.length) {
                            setRegion(regionData?.[0]);
                            setReload(reload+1);
                          }
                        }} 
                        icon={<UndoOutlined title="重置"/>}
                      ></Button>
                    </Space>
                  </section>
              </section>
          </div>
          <Spin spinning={graphLoading} tip="加载中..." style={{width: '100%', height: '100%', display: 'block'}}>
            <div ref={domRef} id={GRAPH_ID} style={{width: '100%', height: 600, position: 'relative', zIndex: 0}} ></div>
          </Spin>
          <HelpTipModal visible={showHelp} setVisible={setShowHelp}/>
          <DetailsModal visible={showDetailModal} setVisible={setShowDetailModal} info={detailInfo}/>
          <MonitorModal visible={showMonitorModal} setVisible={setShowMonitorModal} info={detailInfo}/>
          {showPhysicalAlarmModal && <AssetsAlarm visible={showPhysicalAlarmModal} setVisible={setShowPhysicalAlarmModal} resourceUuid={detailInfo?.label} history={history}/>}
          {showAlarmModal && <ResourceAlarm visible={showAlarmModal} setVisible={setShowAlarmModal} resourceUuid={detailInfo?.uuid} history={history} />}
        </section>
      </section>
    </CmdbContent>
  )
}

export default monitorTopology;

